package com.czf.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @author zfChen
 * @create 2022/6/14 14:25
 */
public class HelloServer {
    public static void main(String[] args) {
        new ServerBootstrap()       //服务启动器，负责组装netty组件
                .group(new NioEventLoopGroup())     //可以简单理解为 线程池 + Selector
                .channel(NioServerSocketChannel.class)  //选择服务 Socket 实现类，其中 NioServerSocketChannel 表示基于 NIO 的服务器端实现
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                                    // 代表和客户端进行读写的通道，负责添加别的handler
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        // 添加具体handler
                        nioSocketChannel.pipeline().addLast(new StringDecoder());   //将bytebuf 转化为字符串
                        nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                System.out.println(msg);
                            }
                        });
                    }
                })
                .bind(8080);  // 绑定监听端口
    }
}
